package com.conferences.web;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.conferences.model.Authority;
import com.conferences.model.User;
import com.conferences.service.UserService;

@Controller
@RequestMapping(value = "registration.htm")
public class RegistrationController {

	@Autowired
	UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public String showForm(ModelMap model) {
		User user = new User();
		model.addAttribute("USER", user);
		return "registration";
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView processForm(@ModelAttribute(value = "USER") User user,
			BindingResult result) {
		if (result.hasErrors()) {
			ModelAndView modelAndView = new ModelAndView("registration");
			return modelAndView;
		}
		
		user.setEnabled((short) 1);
		user.setPassword(md5(user.getPassword()));
		
		Authority authority = new Authority();
		authority.setAuthority("ROLE_USER");
		authority.setUser(user);
		
		List<Authority> auth = new ArrayList<Authority>();
		auth.add(authority);
		user.setAuthorities(auth);
		
		userService.save(user);
		
		ModelAndView modelAndView = new ModelAndView("login");
		modelAndView
				.addObject("msg",
						"Zostałeś poprawnie zarejstrowany w systemie<br/>Możesz się zalogować.");
		return modelAndView;
	}

	private static String md5(String input) {

		String md5 = null;

		if (null == input)
			return null;

		try {

			// Create MessageDigest object for MD5
			MessageDigest digest = MessageDigest.getInstance("MD5");

			// Update input string in message digest
			digest.update(input.getBytes(), 0, input.length());

			// Converts message digest value in base 16 (hex)
			md5 = new BigInteger(1, digest.digest()).toString(16);

		} catch (NoSuchAlgorithmException e) {

			e.printStackTrace();
		}
		return md5;
	}

}
